/*==============================================================================
案例4：生成SHAP分析示例图片（演示版）
作者：张立强
日期：2025-11-03
目的：生成14张PNG示例图片用于PDF展示

注意：这是演示版本，使用模拟数据生成概念性图表
实际分析需要FIFA数据和H2O框架
==============================================================================*/

clear all
set more off
set scheme s2color

// 设置工作目录
cd "/Users/mac/git/stata"

// 创建输出目录
capture mkdir output
capture mkdir output/cases
capture mkdir output/cases/figures

/*------------------------------------------------------------------------------
生成模拟数据（模拟FIFA球员数据）
------------------------------------------------------------------------------*/

clear
set obs 1108
set seed 12345

// 生成位置变量
gen position_num = ceil(uniform()*4)
gen position = ""
replace position = "Forward" if position_num == 1
replace position = "Midfielder" if position_num == 2
replace position = "Defender" if position_num == 3
replace position = "Goalkeeper" if position_num == 4

// 生成年龄（18-35岁）
gen age = 18 + ceil(uniform()*17)

// 生成球队胜率（0.2-0.8）
gen team_win_ratio = 0.2 + uniform()*0.6

// 生成进球效率（0-0.02）
gen goals_per_minute = uniform()*0.02
replace goals_per_minute = goals_per_minute * 2 if position == "Forward"
replace goals_per_minute = goals_per_minute * 0.3 if position == "Defender"
replace goals_per_minute = goals_per_minute * 0.1 if position == "Goalkeeper"

// 生成助攻效率
gen assist_per_minute = uniform()*0.015
replace assist_per_minute = assist_per_minute * 1.5 if position == "Midfielder"

// 生成市场价值（基于特征的复杂函数）
gen base_value = 10 + team_win_ratio*50 + goals_per_minute*1000
gen age_effect = -0.5*(age-26)^2 + 20
gen ln_average_market_value = ln(base_value + age_effect + rnormal(0,5))
gen average_market_value = exp(ln_average_market_value)

// 生成SHAP值（模拟）
gen shap_team_win_ratio = (team_win_ratio - 0.5)*2 + rnormal(0,0.2)
gen shap_age = -0.1*(age-26)^2/10 + rnormal(0,0.1)
gen shap_goals_per_minute = goals_per_minute*50 + rnormal(0,0.1)
gen shap_assist_per_minute = assist_per_minute*30 + rnormal(0,0.1)

/*------------------------------------------------------------------------------
图1：市场价值分布（按位置）
------------------------------------------------------------------------------*/

graph hbox average_market_value, over(position) ///
    title("FIFA Player Market Value by Position") ///
    subtitle("Distribution across 1,108 players") ///
    ytitle("Market Value (Million EUR)") ///
    note("Data source: FIFA 2023 (Simulated)") ///
    scheme(s2color)
graph export "output/cases/figures/case04_01_value_by_position.png", replace width(1200) height(800)

display as result "✓ 图1生成完成: case04_01_value_by_position.png"

/*------------------------------------------------------------------------------
图2：对数价值分布
------------------------------------------------------------------------------*/

histogram ln_average_market_value, ///
    title("Distribution of Log Market Value") ///
    subtitle("After log transformation to handle right skewness") ///
    xtitle("Log(Market Value)") ytitle("Density") ///
    normal ///
    scheme(s2color)
graph export "output/cases/figures/case04_02_log_value_distribution.png", replace width(1200) height(800)

display as result "✓ 图2生成完成: case04_02_log_value_distribution.png"

/*------------------------------------------------------------------------------
图3：变量重要性（模拟）
------------------------------------------------------------------------------*/

clear
input str30 variable float importance
"team_win_ratio" 1.000
"age" 0.856
"goals_per_minute" 0.723
"assist_per_minute" 0.645
"average_minutes_played" 0.512
"height" 0.398
"league_level" 0.367
"nationality_rank" 0.289
"total_yellow_cards" 0.156
"total_red_cards" 0.089
end

graph hbar importance, over(variable, sort(importance) descending) ///
    title("Variable Importance - GBM Model") ///
    subtitle("Relative importance in predicting player market value") ///
    ytitle("Relative Importance") ///
    scheme(s2color) ///
    bar(1, color(navy))
graph export "output/cases/figures/case04_03_variable_importance.png", replace width(1200) height(800)

display as result "✓ 图3生成完成: case04_03_variable_importance.png"

/*------------------------------------------------------------------------------
图4-6：SHAP瀑布图（模拟）
------------------------------------------------------------------------------*/

// 图4：顶级前锋
clear
input str30 feature float shap_value
"Base value" 16.52
"team_win_ratio" 0.85
"goals_per_minute" 0.72
"age" 0.45
"assist_per_minute" 0.23
"average_minutes_played" 0.18
"height" -0.08
"league_level" 0.15
"nationality_rank" 0.12
"total_yellow_cards" -0.05
"Final prediction" 19.25
end

gen cumsum = sum(shap_value)
gen id = _n

graph hbar shap_value, over(feature, sort(id)) ///
    title("SHAP Waterfall Plot - Top Forward") ///
    subtitle("Individual Feature Contributions to Market Value Prediction") ///
    ytitle("SHAP Value (Log Scale)") ///
    scheme(s2color) ///
    bar(1, color(navy))
graph export "output/cases/figures/case04_04_shap_waterfall_forward.png", replace width(1200) height(800)

display as result "✓ 图4生成完成: case04_04_shap_waterfall_forward.png"

// 图5：顶级中场（简化版）
clear
input str30 feature float shap_value
"Base value" 16.52
"team_win_ratio" 0.78
"assist_per_minute" 0.65
"age" 0.52
"goals_per_minute" 0.35
"average_minutes_played" 0.28
"height" 0.05
"league_level" 0.18
"Final prediction" 18.95
end

graph hbar shap_value, over(feature, sort(shap_value)) ///
    title("SHAP Waterfall Plot - Top Midfielder") ///
    subtitle("Individual Feature Contributions") ///
    ytitle("SHAP Value") ///
    scheme(s2color) ///
    bar(1, color(maroon))
graph export "output/cases/figures/case04_05_shap_waterfall_midfielder.png", replace width(1200) height(800)

display as result "✓ 图5生成完成: case04_05_shap_waterfall_midfielder.png"

// 图6：年轻潜力股
clear
input str30 feature float shap_value
"Base value" 16.52
"age" 0.62
"team_win_ratio" 0.45
"goals_per_minute" 0.38
"assist_per_minute" 0.25
"average_minutes_played" -0.15
"height" 0.08
"Final prediction" 17.85
end

graph hbar shap_value, over(feature, sort(shap_value)) ///
    title("SHAP Waterfall Plot - Young Talent (22-24 years)") ///
    subtitle("Individual Feature Contributions") ///
    ytitle("SHAP Value") ///
    scheme(s2color) ///
    bar(1, color(dkgreen))
graph export "output/cases/figures/case04_06_shap_waterfall_young.png", replace width(1200) height(800)

display as result "✓ 图6生成完成: case04_06_shap_waterfall_young.png"

/*------------------------------------------------------------------------------
图7：SHAP蜂群图（模拟）
------------------------------------------------------------------------------*/

clear
set obs 1108
set seed 12345

// 生成10个特征的SHAP值
gen shap_team_win_ratio = rnormal(0.5, 0.4)
gen shap_age = rnormal(0.3, 0.35)
gen shap_goals = rnormal(0.25, 0.3)
gen shap_assist = rnormal(0.2, 0.25)
gen shap_minutes = rnormal(0.15, 0.2)
gen shap_height = rnormal(0.1, 0.15)
gen shap_league = rnormal(0.08, 0.12)
gen shap_nationality = rnormal(0.05, 0.1)
gen shap_yellow = rnormal(-0.02, 0.08)
gen shap_red = rnormal(-0.01, 0.05)

// 创建蜂群图（使用散点图模拟）
gen y1 = 10 + rnormal(0, 0.3)
gen y2 = 9 + rnormal(0, 0.3)
gen y3 = 8 + rnormal(0, 0.3)
gen y4 = 7 + rnormal(0, 0.3)
gen y5 = 6 + rnormal(0, 0.3)

twoway (scatter y1 shap_team_win_ratio, msize(tiny) mcolor(navy%30)) ///
       (scatter y2 shap_age, msize(tiny) mcolor(maroon%30)) ///
       (scatter y3 shap_goals, msize(tiny) mcolor(dkgreen%30)) ///
       (scatter y4 shap_assist, msize(tiny) mcolor(orange%30)) ///
       (scatter y5 shap_minutes, msize(tiny) mcolor(purple%30)), ///
    title("SHAP Summary Plot - All Players (Beeswarm)") ///
    subtitle("Feature Impact Distribution Across 1,108 Observations") ///
    xtitle("SHAP Value (impact on prediction)") ///
    ytitle("Features (ordered by importance)") ///
    ylabel(10 "team_win_ratio" 9 "age" 8 "goals_per_minute" 7 "assist_per_minute" 6 "minutes_played", angle(0)) ///
    legend(off) ///
    scheme(s2color)
graph export "output/cases/figures/case04_07_shap_beeswarm.png", replace width(1200) height(1000)

display as result "✓ 图7生成完成: case04_07_shap_beeswarm.png"

/*------------------------------------------------------------------------------
图8-10：SHAP依赖图
------------------------------------------------------------------------------*/

// 重新加载模拟数据
clear
set obs 1108
set seed 12345

gen team_win_ratio = 0.2 + uniform()*0.6
gen age = 18 + ceil(uniform()*17)
gen goals_per_minute = uniform()*0.02

gen shap_team_win_ratio = (team_win_ratio - 0.5)*2 + rnormal(0,0.2)
gen shap_age = -0.1*(age-26)^2/10 + rnormal(0,0.1)
gen shap_goals_per_minute = goals_per_minute*50 + rnormal(0,0.1)

// 图8：球队胜率依赖图
twoway (scatter shap_team_win_ratio team_win_ratio, mcolor(navy%50) msize(small)) ///
    (lfit shap_team_win_ratio team_win_ratio, lcolor(red) lwidth(thick)), ///
    title("SHAP Dependence Plot: Team Win Ratio") ///
    subtitle("Linear positive relationship") ///
    xtitle("Team Win Ratio") ytitle("SHAP Value") ///
    legend(order(1 "Individual Players" 2 "Trend Line")) ///
    scheme(s2color)
graph export "output/cases/figures/case04_08_shap_dependence_winratio.png", replace width(1200) height(800)

display as result "✓ 图8生成完成: case04_08_shap_dependence_winratio.png"

// 图9：年龄依赖图
twoway (scatter shap_age age, mcolor(navy%50) msize(small)) ///
    (lowess shap_age age, lcolor(red) lwidth(thick)), ///
    title("SHAP Dependence Plot: Age") ///
    subtitle("Inverted U-shape: peak value at 24-27 years") ///
    xtitle("Age (years)") ytitle("SHAP Value") ///
    legend(order(1 "Individual Players" 2 "Trend Line")) ///
    scheme(s2color)
graph export "output/cases/figures/case04_09_shap_dependence_age.png", replace width(1200) height(800)

display as result "✓ 图9生成完成: case04_09_shap_dependence_age.png"

// 图10：进球效率依赖图
twoway (scatter shap_goals_per_minute goals_per_minute, mcolor(navy%50) msize(small)) ///
    (lowess shap_goals_per_minute goals_per_minute, lcolor(red) lwidth(thick)), ///
    title("SHAP Dependence Plot: Goals per Minute") ///
    subtitle("Non-linear positive relationship with increasing marginal returns") ///
    xtitle("Goals per Minute") ytitle("SHAP Value") ///
    legend(order(1 "Individual Players" 2 "Trend Line")) ///
    scheme(s2color)
graph export "output/cases/figures/case04_10_shap_dependence_goals.png", replace width(1200) height(800)

display as result "✓ 图10生成完成: case04_10_shap_dependence_goals.png"

/*------------------------------------------------------------------------------
图11-12：位置对比分析
------------------------------------------------------------------------------*/

// 重新生成完整数据
clear
set obs 1108
set seed 12345

gen position_num = ceil(uniform()*4)
gen position = ""
replace position = "Forward" if position_num == 1
replace position = "Midfielder" if position_num == 2
replace position = "Defender" if position_num == 3
replace position = "Goalkeeper" if position_num == 4

// 生成SHAP值（不同位置有不同模式）
gen shap_goals_per_minute = rnormal(0.4, 0.2) if position == "Forward"
replace shap_goals_per_minute = rnormal(0.2, 0.15) if position == "Midfielder"
replace shap_goals_per_minute = rnormal(0.05, 0.1) if position == "Defender"
replace shap_goals_per_minute = rnormal(0.02, 0.08) if position == "Goalkeeper"

gen shap_team_win_ratio = rnormal(0.5, 0.2) if position == "Forward"
replace shap_team_win_ratio = rnormal(0.45, 0.18) if position == "Midfielder"
replace shap_team_win_ratio = rnormal(0.35, 0.15) if position == "Defender"
replace shap_team_win_ratio = rnormal(0.3, 0.12) if position == "Goalkeeper"

// 图11：进球效率SHAP（按位置）
graph hbox shap_goals_per_minute, over(position) ///
    title("SHAP Values: Goals per Minute by Position") ///
    subtitle("Forwards benefit most from goal-scoring efficiency") ///
    ytitle("SHAP Value") ///
    note("Higher SHAP = Greater positive impact on market value") ///
    scheme(s2color)
graph export "output/cases/figures/case04_11_shap_by_position_goals.png", replace width(1200) height(800)

display as result "✓ 图11生成完成: case04_11_shap_by_position_goals.png"

// 图12：球队胜率SHAP（按位置）
graph hbox shap_team_win_ratio, over(position) ///
    title("SHAP Values: Team Win Ratio by Position") ///
    subtitle("All positions benefit from team success") ///
    ytitle("SHAP Value") ///
    note("Consistent positive impact across all positions") ///
    scheme(s2color)
graph export "output/cases/figures/case04_12_shap_by_position_winratio.png", replace width(1200) height(800)

display as result "✓ 图12生成完成: case04_12_shap_by_position_winratio.png"

/*------------------------------------------------------------------------------
图13-14：交互效应分析
------------------------------------------------------------------------------*/

// 生成年龄组
gen age = 18 + ceil(uniform()*17)
gen age_group = .
replace age_group = 1 if age < 23
replace age_group = 2 if age >= 23 & age < 27
replace age_group = 3 if age >= 27 & age < 30
replace age_group = 4 if age >= 30

label define age_lbl 1 "<23岁" 2 "23-26岁" 3 "27-29岁" 4 "30+岁"
label values age_group age_lbl

// 生成年龄SHAP值（不同位置和年龄组）
gen shap_age = rnormal(0.5, 0.15) if position == "Forward" & age_group == 2
replace shap_age = rnormal(0.3, 0.12) if position == "Forward" & age_group == 1
replace shap_age = rnormal(0.2, 0.1) if position == "Forward" & age_group == 3
replace shap_age = rnormal(-0.1, 0.1) if position == "Forward" & age_group == 4

replace shap_age = rnormal(0.45, 0.15) if position == "Midfielder" & age_group == 2
replace shap_age = rnormal(0.35, 0.12) if position == "Midfielder" & age_group == 1
replace shap_age = rnormal(0.3, 0.1) if position == "Midfielder" & age_group == 3
replace shap_age = rnormal(0.1, 0.1) if position == "Midfielder" & age_group == 4

replace shap_age = rnormal(0.4, 0.15) if position == "Defender" & age_group == 3
replace shap_age = rnormal(0.3, 0.12) if position == "Defender" & age_group == 2
replace shap_age = rnormal(0.2, 0.1) if position == "Defender" & age_group == 1
replace shap_age = rnormal(0.15, 0.1) if position == "Defender" & age_group == 4

replace shap_age = rnormal(0.35, 0.15) if position == "Goalkeeper" & age_group == 3
replace shap_age = rnormal(0.3, 0.12) if position == "Goalkeeper" & age_group == 2
replace shap_age = rnormal(0.25, 0.1) if position == "Goalkeeper" & age_group == 4
replace shap_age = rnormal(0.2, 0.1) if position == "Goalkeeper" & age_group == 1

// 图13：年龄×位置交互
graph bar shap_age, over(age_group) over(position) ///
    title("Age SHAP Values: Position × Age Group Interaction") ///
    subtitle("Different positions have different optimal age ranges") ///
    ytitle("Average SHAP Value") ///
    legend(off) ///
    scheme(s2color)
graph export "output/cases/figures/case04_13_shap_interaction_age_position.png", replace width(1200) height(800)

display as result "✓ 图13生成完成: case04_13_shap_interaction_age_position.png"

// 图14：球队×球员交互
gen team_win_ratio = 0.2 + uniform()*0.6
gen winratio_group = 1 if team_win_ratio < 0.4
replace winratio_group = 2 if team_win_ratio >= 0.4 & team_win_ratio < 0.6
replace winratio_group = 3 if team_win_ratio >= 0.6

label define win_lbl 1 "弱队(<0.4)" 2 "中游(0.4-0.6)" 3 "强队(>0.6)"
label values winratio_group win_lbl

gen goals_per_minute = uniform()*0.02
gen goals_group = 1 if goals_per_minute < 0.007
replace goals_group = 2 if goals_per_minute >= 0.007 & goals_per_minute < 0.014
replace goals_group = 3 if goals_per_minute >= 0.014

label define goals_lbl 1 "低效率" 2 "中等" 3 "高效率"
label values goals_group goals_lbl

gen ln_average_market_value = 16 + rnormal(0,1)
replace ln_average_market_value = ln_average_market_value + 0.5 if winratio_group == 2
replace ln_average_market_value = ln_average_market_value + 1.2 if winratio_group == 3
replace ln_average_market_value = ln_average_market_value + 0.3 if goals_group == 2
replace ln_average_market_value = ln_average_market_value + 0.8 if goals_group == 3
replace ln_average_market_value = ln_average_market_value + 0.5 if winratio_group == 3 & goals_group == 3

graph bar ln_average_market_value, over(goals_group) over(winratio_group) ///
    title("Market Value: Team Success × Player Efficiency") ///
    subtitle("Synergy effect: Strong team + High efficiency = Maximum value") ///
    ytitle("Log(Market Value)") ///
    legend(off) ///
    scheme(s2color)
graph export "output/cases/figures/case04_14_interaction_team_player.png", replace width(1200) height(800)

display as result "✓ 图14生成完成: case04_14_interaction_team_player.png"

/*------------------------------------------------------------------------------
完成总结
------------------------------------------------------------------------------*/

display as result _n(2) "=========================================="
display as result "所有14张SHAP分析图片生成完成！"
display as result "=========================================="
display as text _n "输出目录: output/cases/figures/"
display as text _n "图片清单:"
display as text "  1. case04_01_value_by_position.png"
display as text "  2. case04_02_log_value_distribution.png"
display as text "  3. case04_03_variable_importance.png"
display as text "  4. case04_04_shap_waterfall_forward.png"
display as text "  5. case04_05_shap_waterfall_midfielder.png"
display as text "  6. case04_06_shap_waterfall_young.png"
display as text "  7. case04_07_shap_beeswarm.png"
display as text "  8. case04_08_shap_dependence_winratio.png"
display as text "  9. case04_09_shap_dependence_age.png"
display as text " 10. case04_10_shap_dependence_goals.png"
display as text " 11. case04_11_shap_by_position_goals.png"
display as text " 12. case04_12_shap_by_position_winratio.png"
display as text " 13. case04_13_shap_interaction_age_position.png"
display as text " 14. case04_14_interaction_team_player.png"
display as result _n "=========================================="
display as result "下一步: 运行 ./generate_pdfs.sh 重新生成PDF"
display as result "=========================================="

